import { createWebHistory, createRouter } from 'vue-router';
import { getToken } from '@/api/auth';
import LoginComp from '@/views/login/index.vue';
import Layout from '@/views/Layout.vue';
import Home from '@/views/home/index.vue';
import Err from '@/views/Err.vue';

const routes = [
    {
        path: '/', 
        component: LoginComp,
        meta: {
            isCustomRouter: true,
        }
    },
    {
        path: '/home', 
        component: Layout, 
        name: 'home',
        meta: {
            isCustomRouter: true,
        },
        children: [
            {
                path: '', // 匹配 /home
                component: Home,
                meta: {
                    isCustomRouter: true,
                }
            },
            {
                path: '404', // 匹配 /home/404
                component: Err,
                meta: {
                    isCustomRouter: true,
                }
            }
        ]
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, _, next) => {
    const token = getToken();
    
    // 如果要访问的不是登录页且没有token，则跳转到登录页
    if (to.path !== '/' && !token) {
        next('/');
        return;
    }
    
    // 如果有token且不是访问登录页
    if (token && to.path !== '/') {
        // 检查路由是否存在
        if (to.matched.length > 0) {
            next();
        } else {
            next('/home/404');
        }
    } else {
        // 其他情况（如访问登录页且无token），直接放行
        next();
    }
});

export default router;